//
//  ZDHomeViewController.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/10/27.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDHomeViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "ZDUserAccount.h"
#import "ZDNaviTitleButton.h"
#import "ZDStatus.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "ZDStatusCell.h"
#import "ZDForwardCell.h"
#import "ZDNormalCell.h"
#import "ZDRefreshControl.h"
#import "UIView+ZUtility.h"
#import "ZDPhotoBrowserViewController.h"
#import "ZDPopoverViewController.h"
#import "ZDPresentationController.h"
#import "ZDModalAnimation.h"
#import "ZDDismissAnimation.h"


extern NSString *const ZDPictureViewCellDidSelectNotification;
extern NSString *const ZDPictureViewCellSelectedIndexKey;
extern NSString *const ZDPictureViewCellPhotoBrowserModelKey;

extern NSString *const ZDPopoverViewControllerDismissNotification;

NSString *const NormalCellIdentifier = @"ZDNormalCell";
NSString *const ForwardCellIdentifier = @"ZDForwardCell";

@interface ZDHomeViewController () <UIViewControllerTransitioningDelegate>

@property (nonatomic, strong) NSArray *statuses;

//创建菊花控件
@property (nonatomic, strong) UIActivityIndicatorView *activityView;

//下拉刷新数据加载完成后 提示label
@property (nonatomic, strong) UILabel *tipLabel;

@end

@implementation ZDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //如果没有登录 就直接返回
    if (![ZDUserAccount isLogin])
    {
        return;
    }
    
    //登录成功 设置导航条
    [self prepareNavigationBar];
    
    //设置tableView
    [self prepareTableView];
    
    //设置下拉刷新控件
    [self prepareRefreshControl];
    
    //设置下拉刷新结果提示view
    [self preparePulldownTipView];
    
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pictureViewCellDidSelect:) name:ZDPictureViewCellDidSelectNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popoverViewControllerDismiss) name:ZDPopoverViewControllerDismissNotification object:nil];
}

//注销通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


//通知回调方法
- (void)pictureViewCellDidSelect:(NSNotification *)notification
{
//    ZDLog(@"%@", notification);
    
    NSUInteger index = [notification.userInfo[ZDPictureViewCellSelectedIndexKey] unsignedIntegerValue];
    NSArray *models = notification.userInfo[ZDPictureViewCellPhotoBrowserModelKey];
    
    ZDPhotoBrowserViewController *pbVC = [ZDPhotoBrowserViewController photoBrowserViewControllerWithIndex:index models:models];
    
    //设置pbVC的转场代理为自己  这里不能设置homeController 因为homeController已经做了titleView的转场代理，再设置的话会冲突
    pbVC.transitioningDelegate = pbVC;
    
    //设置modal展示样式为自定义
    pbVC.modalPresentationStyle = UIModalPresentationCustom;
    
    //modal出来
    [self presentViewController:pbVC animated:YES completion:nil];
}

- (void)popoverViewControllerDismiss
{
    ZDNaviTitleButton *btn = (ZDNaviTitleButton *)self.navigationItem.titleView;
    
    [self naviTitleButtonClick:btn];
}


//设置导航条
- (void)prepareNavigationBar
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem addNavigationItem:@"navigationbar_friendsearch" hightlightedImageName:@"navigationbar_friendsearch_highlighted"];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem addNavigationItem:@"navigationbar_pop" hightlightedImageName:@"navigationbar_pop_highlighted"];
    
    
    ZDNaviTitleButton *btn = [[ZDNaviTitleButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    
    [btn setTitle:[ZDUserAccount loadUserAccount].name forState:UIControlStateNormal];
    
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [btn sizeToFit];   //调整控件的size，使其刚好能包装下其子控件  内部会调用sizeThatFits:方法
    
    [btn addTarget:self action:@selector(naviTitleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = btn;
}

//titleButton按钮点击回调方法
- (void)naviTitleButtonClick: (UIButton *)button
{
    CGAffineTransform transform;
    
    //修改按钮的选中状态
    button.selected = !button.isSelected;
    
    //选中状态 就旋转按钮图片 非选中状态 就还原
    transform = button.isSelected ? CGAffineTransformMakeRotation(M_PI - 0.01) : CGAffineTransformIdentity;
    
    /* UIView的旋转 默认采取就近原则，如果旋转M_PI，那么再旋转回来时，是顺时针；这里我们想让她逆时针旋转回来，我们可以修改旋转角度 让它略小于M_PI */
    
    [UIView animateWithDuration:0.25 animations:^{
        
        button.imageView.transform = transform;
    }];
    
    
    //modal出popover视图
    if (button.selected)
    {
        ZDPopoverViewController *popoverVC = [[ZDPopoverViewController alloc] init];
        
        //设置转场代理
        popoverVC.transitioningDelegate = self;
        
        //设置modal的展现样式为自定义
        popoverVC.modalPresentationStyle = UIModalPresentationCustom;
        
        //modal出来
        [self presentViewController:popoverVC animated:YES completion:nil];
    }
}


#pragma mark - UIViewControllerTransitioningDelegate代理方法
//返回modal视图的展现控制器 ———— 就是制定modal出来的视图长什么样子
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    return [[ZDPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
}

//返回控制器modal出来的动画对象  只要遵守UIViewControllerAnimatedTransitioning协议即可 ———— 制定modal出来的动画
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[ZDModalAnimation alloc] init];
}

//返回控制器dismiss的动画对象
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[ZDDismissAnimation alloc] init];
}




- (void)prepareTableView
{
    self.tableView.estimatedRowHeight = 300;
    
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = self.activityView;
    
    //注册cell
    [self.tableView registerClass:[ZDForwardCell class] forCellReuseIdentifier:ForwardCellIdentifier];
    
    [self.tableView registerClass:[ZDNormalCell class] forCellReuseIdentifier:NormalCellIdentifier];
}


- (void)prepareRefreshControl
{
    self.refreshControl = [[ZDRefreshControl alloc] init];
    
    //为刷新控件添加事件 只有下拉到系统控件开始refreshing时才会触发该方法
    [self.refreshControl addTarget:self action:@selector(loadStatuses) forControlEvents:UIControlEventValueChanged];
    
    //设置一进入界面就开始刷新
    [self.refreshControl beginRefreshing];  //只是进入刷新状态 并不会触发valueChanged回调方法
    
    //设置代码触发valueChanged回调方法
    [self.refreshControl sendActionsForControlEvents:UIControlEventValueChanged];
}


- (void)preparePulldownTipView
{
    //添加子控件
    [self.navigationController.navigationBar insertSubview:self.tipLabel atIndex:0];
    
    //设置frame  navigatonBar的高度是44 加上状态栏的20 才是64
//    self.tipLabel.frame = self.navigationController.navigationBar.bounds;
    self.tipLabel.frame = CGRectMake(0, -64, ZDScreenSize.width, 44);
    
}


- (void)tipLabelAnimation:(NSUInteger)count
{
    self.tipLabel.text = count ? [NSString stringWithFormat:@"更新了%ld条微博", count] : @"没有微博更新";
    
    [UIView animateWithDuration:0.75 animations:^{
      
        self.tipLabel.frame = CGRectMake(0, 44, ZDScreenSize.width, 44);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.75 delay:0.25 options:0 animations:^{
            
            self.tipLabel.frame = CGRectMake(0, -64, ZDScreenSize.width, 44);
            
        } completion:^(BOOL finished) {
            
//            [self.tipLabel removeFromSuperview];
        }];
    }];
}

//加载微博数据
- (void)loadStatuses
{
    //数组最前免得数据代表最新的微博，展示在tableView的最上面
    ZDStatus *newStatus = self.statuses.firstObject;
    ZDStatus *oldStatus = self.statuses.lastObject;
    
    //默认是下拉刷新
    int64_t since_id = newStatus.id;
    int64_t max_id = 0;
    
    //上拉加载
    if (_activityView.isAnimating)
    {
        since_id = 0;
        max_id = oldStatus.id;
    }
    
    [ZDStatus loadStatusesWithSince_id:since_id max_id:max_id success:^(NSArray *result) {
        
        //加载到数据后 停止刷新
        [self.refreshControl endRefreshing];
        [self.activityView stopAnimating];
        
        if (since_id > 0)  //下拉刷新
        {
            //拼接数组  新加载到的数据放在数组前面  加载到时间更新的微博
            self.statuses = [result arrayByAddingObjectsFromArray:self.statuses];
            
            ZDLog(@"下拉刷新加载到%ld条数据", result.count);
            
            [self tipLabelAnimation:result.count];
        }
        else if (max_id > 0)   //下拉加载
        {
            //拼接数组  新加载到的数据放在数组后面  加载到时间更早的微博
            self.statuses = [self.statuses arrayByAddingObjectsFromArray:result];
            
            ZDLog(@"上拉加载到%ld条数据", result.count);
        }
        else
        {
            self.statuses = result;    //第一次默认加载20条数据
            
            ZDLog(@"第一次默认加载%ld条数据", result.count);
        }
        
        //刷新tableView
        [self.tableView reloadData];
//        ZDLog(@"statuses: %@", self.statuses);
        
    } failure:^(NSError *error) {
        
        [SVProgressHUD showInfoWithStatus:@"加载微博数据出错" maskType:SVProgressHUDMaskTypeNone];
        
        //加载数据失败也要停止刷新
        [self.refreshControl endRefreshing];
//FIXME: 上拉加载如果失败  只是菊花隐藏  tableFooterView的那段空白仍然在
        [self.activityView stopAnimating];
        
    }];
}




#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    ZDLog(@"count = %ld", self.statuses.count);
    
    return self.statuses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDStatus *status = self.statuses[indexPath.row];
    
    ZDStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:status.identifier];
    
//    //如果没有注册cell 就需要如下动手创建；如果已经注册cell，则如下代码可以省略，系统会自动调用自定义cell的initWithStyle:方法
//    if (!cell)
//    {
//        cell = [[ZDStatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NormalCellIdentifier];
//    }
    
    cell.status = status;
    
    //显示最后一行时 开始加载
    if (indexPath.row == self.statuses.count - 1 && !_activityView.isAnimating)
    {
        [_activityView startAnimating];
        
        //加载数据
        [self loadStatuses];
    }
    
    return cell;
}

//返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDStatus *status = self.statuses[indexPath.row];
    
    if (status.rowHeight)
    {
//        ZDLog(@"从缓存加载");
        return status.rowHeight;
    }
    
    ZDStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:status.identifier];
    
//    ZDLog(@"计算行高");
    
    CGFloat rowHeight = [cell rowHeight:status];
    
    status.rowHeight = rowHeight;

//    ZDLog(@"cell:%lf", rowHeight);
    
    return rowHeight;
}


#pragma mark 懒加载
- (UIActivityIndicatorView *)activityView
{
    if (!_activityView)
    {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        
        _activityView.color = [UIColor grayColor];
        
        _activityView.frame = CGRectMake(0, 0, ZDScreenSize.width, 44);
        
    }
    
    return _activityView;
}


- (UILabel *)tipLabel
{
    if (!_tipLabel)
    {
        _tipLabel = [[UILabel alloc] init];
        
        _tipLabel.backgroundColor = [UIColor orangeColor];
        
        _tipLabel.textColor = [UIColor whiteColor];
        
        _tipLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return _tipLabel;
}

@end
